﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Web;

namespace GodSoft.Code
{
    /// <summary>
    ///包含杂项功能的类
    /// </summary>
    public class Utilities
    {
        //用于发送电子邮件的通用方法
        public static void SendMail(string from, string to, string subject, string body)
        {
            string smtpServer = "smtp.qq.com";
            // 邮件服务设置
            SmtpClient smtpClient = new SmtpClient();
            smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;//指定电子邮件发送方式
            smtpClient.Host = smtpServer; //指定SMTP服务器
            smtpClient.EnableSsl = true;
            //用户名和密码
            smtpClient.Credentials = new System.Net.NetworkCredential(GodSoftConfiguration.MailUserName, GodSoftConfiguration.MailPassWord);

            // 发送邮件设置        
            MailMessage mailMessage = new MailMessage(from, to); // 发送人和收件人
            mailMessage.Subject = subject;//主题
            mailMessage.Body = body;//内容
            mailMessage.SubjectEncoding = System.Text.Encoding.GetEncoding("gb2312");
            mailMessage.BodyEncoding = System.Text.Encoding.GetEncoding("gb2312");
            mailMessage.IsBodyHtml = true;//设置为HTML格式
            mailMessage.Priority = MailPriority.Low;//优先级
            smtpClient.Send(mailMessage); // 发送邮件

        }

        //发送错误日志
        public static void LogError(Exception ex)
        {
            //获取当前时间和日期
            string datetime = DateTime.Now.ToLongDateString();
            //存储错误消息
            string errorMessage = "异常产生于: <br/>" + datetime;
            //获取产生错误的页面
            System.Web.HttpContext context = System.Web.HttpContext.Current;
            errorMessage += "<br/> 错误页面地址:<br/>" + context.Request.RawUrl;
            //构建错误消息
            errorMessage += "<br/> 消息：<br/>" + ex.Message;
            errorMessage += "<br/> 错误源：<br/>" + ex.Source;
            errorMessage += "<br/> 目的网站：<br/>" + ex.TargetSite;
            errorMessage += "<br/> 堆栈跟踪:<br/>" + ex.StackTrace;
            if (GodSoftConfiguration.EnableErrorLogEmail)
            {
                string from = GodSoftConfiguration.MailFrom;
                string to = GodSoftConfiguration.ErrorLogEmail;
                string subject = "路灯平台错误报告";
                string body = errorMessage;
                SendMail(from, to, subject, body);
            }

        }
    }
}